using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using VistaBatterySaver.Properties;
using System.Reflection;
using Microsoft.Win32;
using System.Runtime.InteropServices;
using System.Threading;

namespace VistaBatterySaver
{
    public partial class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();
            Hide();

            PowerMngr.IsSidebarActiveOnStartup = Helper.IsSidebarRunning;

            initSettings();
           

            if (Settings.Default.LastLocation == new Point(-1, -1))
                Settings.Default.LastLocation = new Point(Screen.PrimaryScreen.Bounds.Width / 2 - Width / 2,
                    Screen.PrimaryScreen.Bounds.Height / 2 - Height / 2);

            this.Location = Settings.Default.LastLocation;

            
        }

        protected override void OnHandleCreated(EventArgs e)
        {
            base.OnHandleCreated(e);
            PowerMngr.GetManager().RegisterForPowerNotifications(this.Handle);
            
        }

        protected override void WndProc(ref Message m)
        {
            base.WndProc(ref m);

            if (m.Msg == PowerMngr.WM_POWERBROADCAST)
            {
                PowerMngr.GetManager().PowerSettingChange(m);
            }
        }

        void initSettings()
        {
            rbAeroOn.Checked = Settings.Default.AeroActive == 0;
            rbAeroOff.Checked = Settings.Default.AeroActive == 1;
            rbAeroLess.Checked = Settings.Default.AeroActive == 2;
            nudAero.Value = Settings.Default.AeroActiveLevel;

           
            alwaysDeactivateOnBatteryToolStripMenuItem.Image = rbAeroOn.Checked ? Resources.checkMark : null;
            neverDeactivateOnBatteryToolStripMenuItem.Image = rbAeroOff.Checked ? Resources.checkMark : null;


            rbSidebarOn.Checked = Settings.Default.SidebarActive == 0;
            rbSidebarOff.Checked = Settings.Default.SidebarActive == 1;
            rbSidebarLess.Checked = Settings.Default.SidebarActive == 2;
            nudSidebar.Value = Settings.Default.SidebarActiveLevel;

            alwaysDeactivateOnBatteryToolStripMenuItem1.Image = rbSidebarOn.Checked ? Resources.checkMark : null;
            neverDeactivateOnBatteryToolStripMenuItem1.Image = rbSidebarOff.Checked ? Resources.checkMark : null;

            

            cbNotifyShow.Checked = Settings.Default.DisableNotifications;

            cbStartup.Checked = Settings.Default.RunInStartup;

            cbCheck.Checked = Settings.Default.UpdateInStartup;

            gbSidebar.Enabled = PowerMngr.IsSidebarActiveOnStartup;
            gbAero.Enabled = Helper.IsVistaAeroSupport;

            windowsSidebarToolStripMenuItem.Visible = gbSidebar.Enabled;
            windowsAeroToolStripMenuItem.Visible = gbAero.Enabled;

            initPlans();
            //cbBut.DataSource = plans;
            //cbPlug.DataSource = plans;

            cbBut.Items.Clear();
            cbPlug.Items.Clear();
            for (int i = 0; i< plans.Count; i++)
            {
                cbPlug.Items.Add(plans[i]);
                cbBut.Items.Add(plans[i]);
                cbIdle.Items.Add(plans[i]);
            }

            if (Settings.Default.PWBattery == Guid.Empty & Settings.Default.PWPlug == Guid.Empty & Settings.Default.PWIdle == Guid.Empty)
            {
                cbBut.SelectedIndex = plans.IndexOf(new PowerPlan(Helper.GetActivePower()));
                cbPlug.SelectedIndex = plans.IndexOf(new PowerPlan(Helper.GetActivePower()));
                cbIdle.SelectedIndex = plans.IndexOf(new PowerPlan(Helper.GetActivePower()));
            }
            else
            {
                
                for(int i=0;i<plans.Count;i++)
                {
                    if(plans[i].Id == Settings.Default.PWBattery)
                        cbBut.SelectedIndex = i;
                    if(plans[i].Id == Settings.Default.PWPlug)
                        cbPlug.SelectedIndex = i;
                    if (plans[i].Id == Settings.Default.PWIdle)
                        cbIdle.SelectedIndex = i;
                }
                
            }
        }

        void initPlans()
        {
            plans = new List<PowerPlan>();
            Dictionary<Guid, string> pls = Helper.GetPowerEnumeration();

            foreach(KeyValuePair<Guid,string> pl in pls)
            { 
                plans.Add(new PowerPlan(pl));
            }
        }

        List<PowerPlan> plans = new List<PowerPlan>();

        class PowerPlan
        {
            private PowerPlan() { }

            public PowerPlan(KeyValuePair<Guid, string> val)
            {
                m_id = val.Key;
                m_name = val.Value;
            }

            private string m_name;

            public string Name
            {
                get { return m_name; }
                set { m_name = value; }
            }

            private Guid m_id;

            public Guid Id
            {
                get { return m_id; }
                set { m_id = value; }
            }

            public override string ToString()
            {
                return m_name;
            }

            public override bool Equals(object obj)
            {
                if(obj is PowerPlan)
                    return m_id.Equals(((PowerPlan)obj).Id);

                return base.Equals(obj);
            }

            public override int GetHashCode() {
               return base.GetHashCode();
            }
        }

        void saveSettings()
        {
            Helper.RunInStartup = cbStartup.Checked;


            if (rbAeroOn.Checked) Settings.Default.AeroActive = 0;
            if (rbAeroOff.Checked) Settings.Default.AeroActive = 1;
            if (rbAeroLess.Checked) Settings.Default.AeroActive = 2;
            Settings.Default.AeroActiveLevel = nudAero.Value;

            

            if (rbSidebarOn.Checked) Settings.Default.SidebarActive = 0;
            if (rbSidebarOff.Checked) Settings.Default.SidebarActive = 1;
            if (rbSidebarLess.Checked) Settings.Default.SidebarActive = 2;
            Settings.Default.SidebarActiveLevel = nudSidebar.Value;

            

            Settings.Default.DisableNotifications = cbNotifyShow.Checked;

            Settings.Default.RunInStartup = cbStartup.Checked;

            Settings.Default.UpdateInStartup = cbCheck.Checked;

            gbSidebar.Enabled = PowerMngr.IsSidebarActiveOnStartup;
            gbAero.Enabled = Helper.IsVistaAeroSupport;

            windowsSidebarToolStripMenuItem.Visible = gbSidebar.Enabled;
            windowsAeroToolStripMenuItem.Visible = gbAero.Enabled;

            Settings.Default.PWBattery = ((PowerPlan)cbBut.SelectedItem).Id;
            Settings.Default.PWPlug = ((PowerPlan)cbPlug.SelectedItem).Id;
            Settings.Default.PWIdle = ((PowerPlan)cbIdle.SelectedItem).Id;

            Settings.Default.Save();
        }

        internal void SetStatus(bool isAero, bool isSidebar)
        {
            if (this.InvokeRequired)
            {
                this.BeginInvoke((SendOrPostCallback)delegate
                {
                    SetStatus(isAero, isSidebar);
                }, null);
            }
            else
            {
                string newAeroStr = isAero ? Resources.strOn : Resources.strOff;
                string newSidebarStr = isSidebar ? Resources.strOn : Resources.strOff;

                

                lblAeroStatus.Text = newAeroStr;
                lblSidebarStatus.Text = newSidebarStr;
            }
        }

        

        

       

        private void rbAero_CheckedChanged(object sender, EventArgs e)
        {
            tbAero.Enabled = nudAero.Enabled = lblAeroP.Enabled = rbAeroLess.Checked;

            if (rbAeroOn.Checked | rbAeroOff.Checked)
            {
                Settings.Default.AeroActive = rbAeroOn.Checked ? (byte)0 : (byte)1;
                PowerMngr.GetManager().HandleAero(SystemInformation.PowerStatus.PowerLineStatus == PowerLineStatus.Online);
            }
            else if(rbAeroLess.Checked)
            {
                Settings.Default.AeroActive = 2;
                PowerMngr.GetManager().HandleAero(Settings.Default.AeroActiveLevel < (decimal)(SystemInformation.PowerStatus.BatteryLifePercent * 100));
            }

            

        }

        private void rbSidebar_CheckedChanged(object sender, EventArgs e)
        {
            tbSidebar.Enabled = nudSidebar.Enabled = lblSidebarP.Enabled = rbSidebarLess.Checked;

            if (rbSidebarOn.Checked | rbSidebarOff.Checked)
            {
                Settings.Default.SidebarActive = rbSidebarOn.Checked ? (byte)0 : (byte)1;
                PowerMngr.GetManager().HandleSidebar(SystemInformation.PowerStatus.PowerLineStatus == PowerLineStatus.Online);
            }
            else if (rbSidebarLess.Checked)
            {
                Settings.Default.SidebarActive = 2;
                PowerMngr.GetManager().HandleSidebar(Settings.Default.SidebarActiveLevel < (decimal)(SystemInformation.PowerStatus.BatteryLifePercent * 100));
            }

        }

        private void tbAero_Scroll(object sender, EventArgs e)
        {
            nudAero.Value = tbAero.Value;
        }

        private void tbSidebar_Scroll(object sender, EventArgs e)
        {
            nudSidebar.Value = tbSidebar.Value;
        }

        private void nudAero_ValueChanged(object sender, EventArgs e)
        {
            tbAero.Value = (int)nudAero.Value;

            if (rbAeroLess.Checked)
            {
                Settings.Default.AeroActive = 2;
                PowerMngr.GetManager().HandleAero(Settings.Default.AeroActiveLevel < (decimal)(SystemInformation.PowerStatus.BatteryLifePercent * 100));
            }
        }

        private void nudSidebar_ValueChanged(object sender, EventArgs e)
        {
            tbSidebar.Value = (int)nudSidebar.Value;

            if (rbSidebarLess.Checked)
            {
                Settings.Default.SidebarActive = 2;
                PowerMngr.GetManager().HandleSidebar(Settings.Default.SidebarActiveLevel < (decimal)(SystemInformation.PowerStatus.BatteryLifePercent * 100));
            }
        }

        private void notifyIcon_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                notifyIcon.ContextMenuStrip = cmsOperation;
            }
            else
            {
                notifyIcon.ContextMenuStrip = cmsMain;
            }
            notifyIcon.GetType().InvokeMember(
      "ShowContextMenu",
            BindingFlags.InvokeMethod | 
            BindingFlags.Instance | 
            BindingFlags.NonPublic,
              null,
              notifyIcon,
              null
        );

        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            PowerMngr.GetManager().UnregisterForPowerNotifications();
            Application.Exit();
        }
       
        private void showMain(object sender, EventArgs e)
        {
            if(notifyIcon.ContextMenuStrip != null)
                notifyIcon.ContextMenuStrip.Hide();
            Show();
            WindowState = FormWindowState.Normal;
            Focus();
            Activate();
        }

        private void frmMain_HelpRequested(object sender, EventArgs hlpevent)
        {

        }

        protected override void OnClosing(CancelEventArgs e)
        {
            Hide();

            Settings.Default.LastLocation = this.Location;

            e.Cancel = true;
            base.OnClosing(e);
        }

        private void menuItemSidebar_Click(object sender, EventArgs e)
        {
            bool sidebarBattery = sender == alwaysDeactivateOnBatteryToolStripMenuItem;
            alwaysDeactivateOnBatteryToolStripMenuItem1.Image = sidebarBattery ? Resources.checkMark : null;
            neverDeactivateOnBatteryToolStripMenuItem1.Image = !sidebarBattery ? Resources.checkMark : null;

            rbSidebarOn.Checked = sidebarBattery;
            rbSidebarOff.Checked = !sidebarBattery;
        }

        private void menuItemAeroClick(object sender, EventArgs e)
        {
            bool aeroBattery = sender == alwaysDeactivateOnBatteryToolStripMenuItem;
            alwaysDeactivateOnBatteryToolStripMenuItem.Image = aeroBattery ? Resources.checkMark : null;
            neverDeactivateOnBatteryToolStripMenuItem.Image = !aeroBattery ? Resources.checkMark : null;

            rbAeroOn.Checked  = aeroBattery;
            rbAeroOff.Checked = !aeroBattery;
        }

        private void btApply_Click(object sender, EventArgs e)
        {
            saveSettings();

            this.Close();
        }

        private void btCancel_Click(object sender, EventArgs e)
        {
            initSettings();

            this.Close();
        }

        private void gbSidebar_EnabledChanged(object sender, EventArgs e)
        {
            if (!gbSidebar.Enabled & !Settings.Default.DisableNotifications)
            {
                notifyIcon.ShowBalloonTip(5000, Resources.msgSidebarNotRunningTitle, Resources.msgSidebarNotRunning.Replace('|','\n'), ToolTipIcon.Info);
                notifyIcon.BalloonTipClicked += new EventHandler(disableMessage_BalloonTipClicked);
                notifyIcon.BalloonTipClosed += new EventHandler(disableMessage_BalloonTipClosed);
            }
        }

        void disableMessage_BalloonTipClicked(object sender, EventArgs e)
        {
            gbSidebar.Enabled = true;
            PowerMngr.IsSidebarActiveOnStartup = true;
            windowsSidebarToolStripMenuItem.Visible = gbSidebar.Enabled;
            showMain(this, null);
        }

        void disableMessage_BalloonTipClosed(object sender, EventArgs e)
        {
            notifyIcon.BalloonTipClicked -= new EventHandler(disableMessage_BalloonTipClicked);
            notifyIcon.BalloonTipClosed -= new EventHandler(disableMessage_BalloonTipClosed);
        }

        private void gbAero_EnabledChanged(object sender, EventArgs e)
        {
            if (!gbAero.Enabled & !Settings.Default.DisableNotifications)
            {
                notifyIcon.ShowBalloonTip(5000, Resources.msgAeroNotRunningTitle, Resources.msgAeroNoRunning.Replace('|', '\n'), ToolTipIcon.Info);
            }
        }

        internal void ShowAeroMessage(bool isEnabled)
        {
            if (this.InvokeRequired)
            {
                this.BeginInvoke((SendOrPostCallback)delegate
                {
                    ShowAeroMessage(isEnabled);
                }, null);
            }
            else
            {
                if (!Settings.Default.DisableNotifications)
                {
                    notifyIcon.ShowBalloonTip(5000,
                        isEnabled ? Resources.msgAeroEnabled : Resources.msnAeroDisabled, string.Empty,
                        ToolTipIcon.Info);
                }
            }
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (frmAbout f = new frmAbout())
            {
                f.ShowDialog();
            }
        }

        private void checkForUpdatesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (Helper.HasNewUpdates(Settings.Default.CurrentBuild) &&
                    MessageBox.Show(Resources.msgNewVersion.Replace('|', '\n'), Resources.msgNewVersionTitle, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    Helper.InstallNewVersion();
                }
            }
            catch { }
        }

        

        

       


        
    }
}